import { useState, useEffect, useRef, useMemo, useCallback } from 'react'
import { IconSty, UploadImgFrameSty } from './style';
import { PlusOutlined } from '@ant-design/icons';
import { Button } from 'antd';
export default function BlobUse() {
  const [imgUrl, setImgUrl] = useState('')
  const [isShow, setIsShow] = useState(false)
  const inputDom = useRef(null)

  const selectFile = useCallback((e: any) => {
    //blob
    if (imgUrl) {
      window.URL.revokeObjectURL(imgUrl)
    }
    const url = window.URL.createObjectURL(e.target.files[0]);
    setImgUrl(url)
    setIsShow(true)

    //base64
    // const file = e.target.files[0];
    // const reader = new FileReader();
    // reader.readAsDataURL(file);
    // reader.onload = () => {
    //   setImgUrl(reader.result as string);
    //   setIsShow(true);
    // };
  }, [imgUrl])

  const clickDownload = useCallback(() => {
    const data = {
      name: '张三',
      age: 18,
      second: "我不会出现在下载的数据中",
    };
    downloadJson(data, "json.json");
  }, [])


  /** 下载JSON文件*/
  const downloadJson = useCallback((data: any, filename: string) => {
    if (!data) {
      alert("保存的数据为空");
      return;
    }

    if (!filename) {
      filename = "json.json";
    }
    if (typeof data === "object") {
      data = JSON.stringify(data, null, 4);
    }
    let blob = new Blob([data], { type: "text/json" });

    //创建一个a标签进行下载
    let a = document.createElement("a");
    a.download = filename;
    a.href = window.URL.createObjectURL(blob);
    a.click();
    URL.revokeObjectURL(a.href);
  }, [])

  useEffect(() => {
    return () => {
      imgUrl && window.URL.revokeObjectURL(imgUrl)
    }
  }, [])

  return (
    <>
      <h3>Blob 实现本地图片预览</h3>
      <UploadImgFrameSty>
        {
          !isShow && <IconSty>
            <PlusOutlined />
          </IconSty>
        }
        <input ref={inputDom} type="file" onChange={selectFile} accept="image/*" />
        {isShow && <img src={imgUrl} />}
      </UploadImgFrameSty>

      <h3>下载JSON文件</h3>
      <Button type="primary" onClick={clickDownload}>下载JSON文件</Button>
    </>
  )
}